
#include <stdio.h>
#include <zookeeper/zookeeper.h>
#include <unistd.h>

// 全局变量用于控制事件循环
static int connected = 0;

// 连接状态回调函数
void connection_watcher(zhandle_t *zh, int type, int state, const char *path, void* context) {
    if (state == ZOO_CONNECTED_STATE) {
        connected = 1;
    }
}

// 异步创建节点回调
void create_completion(int rc, const char *name, const void *data) {
    printf("Create result: [rc:%d] [path:%s] [ctx:%s]\n", 
           rc, name, (const char*)data);
}

// 异步获取数据回调
void data_completion(int rc, const char *value, int value_len, 
                    const struct Stat *stat, const void *data) {
    printf("Data result: [rc:%d] [data:%.*s] [ctx:%s]\n",
           rc, value_len, value, (const char*)data);
}

int main() {
    const char* hosts = "localhost:2181";
    zhandle_t *zh = zookeeper_init(hosts, connection_watcher, 30000, 0, NULL, 0);
    
    // 等待连接建立
    while(!connected) { 
        usleep(1000); 
    }

    // 异步创建节点（EPHEMERAL类型）
    zoo_acreate(zh, "/test_async_node", "init_data", 9, 
               &ZOO_OPEN_ACL_UNSAFE, ZOO_EPHEMERAL,
               create_completion, "create_ctx");

    // 异步获取节点数据
    zoo_aget(zh, "/test_async_node", 0, data_completion, "get_ctx");

    // 保持运行以接收回调
    sleep(1000);
    zookeeper_close(zh);
    return 0;
}
